import { Component } from '@angular/core';
import {IonicPage, NavController} from 'ionic-angular';
import {InfoProvider} from "../../providers/InfoProvider";
import {CommProvider} from "../../providers/CommProvider";
import {HttpService} from "../../providers/HttpService";
import {SocketService} from "../../providers/SocketService";

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

    prevStyleIndex = -1;
    grid_style_list: Array<any> = [];
    grid_style_list2: Array<any> = [];
    range_style_list: Array<any> = [];

    user_info: any;
    mobileConfig: any;
    quotation_list: Array<any> = [];

    news_type: string = 'comm_news';
    tab_position: number = 0;
    tab_list: any[] = [
        {
            title: '要闻',
            value: 'comm_news',
            key: 1
        },
        {
            title: '贵金属',
            value: 'gold_news',
            key: 8
        }
    ];
    news_list: Array<any> = [];

    constructor(public navCtrl: NavController,
                private infoProvider: InfoProvider,
                private commProvider: CommProvider,
                private httpService: HttpService,
                private socketService: SocketService) {
        this.user_info = this.infoProvider.getUserInfo();
        for (let i = 0; i < this.tab_list.length; i++) {
            let subInfoList: Array<any> = [];
            this.news_list.push(subInfoList);
        }
    }

    ionViewWillLoad() {

    }

    async ionViewDidLoad() {
        let result = await this.httpService.instance()
          .setUrl('/system/getMobileConfig')
          .getRequest();

        if (result) {
            if (result.status == 0) {
                this.mobileConfig = result.data;
                this.infoProvider.setMobileConfig(this.mobileConfig);

                if (this.mobileConfig.qtt_push == 1) {
                    this.socketService.connectRemoteServer((key, data) => {
                      for (let i = 0; i < this.quotation_list.length; i++) {
                        let quotation = this.quotation_list[i];
                        if (quotation.key == key) {
                          // console.log('quotationPushH5 index:', i);
                          // console.log('quotationPushH5 name:', quotation.name);
                          // console.log('quotationPushH5 data:', data);
                          this.updateGridStyle(i, data);
                          break;
                        }
                      }
                    });
                }

                for (let i = 0; i < this.mobileConfig.quotation_number; i++) {
                    this.quotation_list.push();
                }
            }

            this.getQuotation('gjs').then(result => {
                for (let i = 0; i < this.mobileConfig.quotation_number; i++) {
                    this.quotation_list[i] = result[i];
                }
                console.log(this.quotation_list);
            });

            this.getNewsByChannel(this.tab_position).then(res => {
                if (res.status == 0) {
                    this.news_list[this.tab_position] = res.data.pager.result;
                }
            });

            if (this.mobileConfig.activity && this.mobileConfig.activity.show) {
                setTimeout(() => {
                    this.commProvider.showDialogModal('ActivityModalPage');
                }, 2000);
            }
        }

        /*this.httpService.instance()
            .setUrl('/system/getMobileConfig')
            .getRequest()
            .then(res => {
                if (res.status == 0) {
                    this.mobileConfig = res.data;
                    for (let i = 0; i < this.mobileConfig.quotation_number; i++) {
                        this.quotation_list.push();
                    }

                    this.getQuotation('gjs').then(result => {
                        for (let i = 0; i < this.mobileConfig.quotation_number; i++) {
                            /!*let data = result[i];
                            if (data.key == 'XAU') {
                                data.name = '黄金';
                                this.quotation_list[0] = data;
                            } else if (data.key == 'XAG') {
                                data.name = '白银';
                                this.quotation_list[1] = data;
                            } else if (data.key == 'XAP') {
                                data.name = '铂金';
                                this.quotation_list[2] = data;
                            }*!/
                            this.quotation_list[i] = result[i];
                        }
                        console.log(this.quotation_list);
                    });

                    this.getNewsByChannel(this.tab_position).then(res => {
                        if (res.status == 0) {
                            this.news_list[this.tab_position] = res.data.pager.result;
                        }
                    });

                    if (this.mobileConfig.activity && this.mobileConfig.activity.show) {
                        setTimeout(() => {
                            this.commProvider.showDialogModal('ActivityModalPage');
                        }, 2000);
                    }
                }
            });*/
    }

    setGridLayoutStyle(index: number) {
        this.grid_style_list.push({});
        return this.grid_style_list[index];
    }

    setGridLayoutStyle2(index: number) {
        this.grid_style_list2.push({});
        return this.grid_style_list2[index];
    }

    setGridListStyle(index: number) {
        if (this.mobileConfig.quotation_number == 3) {
            return {
                'grid-item-left': (index % 3) == 0,
                'grid-item-center': (index % 3) == 1,
                'grid-item-right': (index % 3) == 2
            };
        } else {
            return {
                'grid-item-left2': (index % 2) == 0,
                'grid-item-right2': (index % 2) == 1
            };
        }

    }

    setGridItemPrice(range: string) {
        let value = Number(range);
        return {
            'price-normal': value == 0,
            'price-up': value > 0,
            'price-down': value < 0,
        };
    }

    setGridItemRange(index: number, range: string) {
        let value = Number(range);
        this.range_style_list.push({
            'range-normal': value == 0,
            'range-up': value > 0,
            'range-down': value < 0,
        });
        return this.range_style_list[index];
    }

    updateGridStyle(index: number, data: Array<any>) {
        this.quotation_list[index].tradePrice = data[0];
        this.quotation_list[index].range = data[5];
        this.quotation_list[index].rangePercent = data[6];
        let value = Number(data[5]);
        this.range_style_list[index] = {
            'range-normal': value == 0,
            'range-up': value > 0,
            'range-down': value < 0,
        };

        if (this.prevStyleIndex != index) {
            this.grid_style_list[index] = {
                'normal-grid-layout': value == 0,
                'up-grid-layout': value > 0,
                'down-grid-layout': value < 0,
            };
            if (this.prevStyleIndex >= 0) {
                this.grid_style_list[this.prevStyleIndex] = {};
                this.grid_style_list2[this.prevStyleIndex] = {};
            }
        } else {
            if (this.grid_style_list[index].hasOwnProperty('normal-grid-layout')) {
                this.grid_style_list[index] = {};
                this.grid_style_list2[index] = {
                    'normal-grid-layout': value == 0,
                    'up-grid-layout': value > 0,
                    'down-grid-layout': value < 0,
                };
            } else if (this.grid_style_list2[index].hasOwnProperty('normal-grid-layout')) {
                this.grid_style_list2[index] = {};
                this.grid_style_list[index] = {
                    'normal-grid-layout': value == 0,
                    'up-grid-layout': value > 0,
                    'down-grid-layout': value < 0,
                };
            }
        }

        this.prevStyleIndex = index;
    }

    onTodayStrategy() {
        if (this.user_info.type > 0) {
            this.navCtrl.push('TodayStrategyPage');
        } else if (this.user_info.type < 0) {
            this.commProvider.showToast('请先登录');
        } else {
            this.commProvider.showToast('您还不是VIP用户');
        }
    }

    onBecameMember() {
        if (this.user_info.type < 0) {
            this.navCtrl.push('LoginPage', {guest_login: true});
        } else {
            this.navCtrl.push('MemberPage');
        }
    }

    onVipTrade() {
        if (this.user_info.type > 0) {
            this.navCtrl.push('VipTradePage');
        } else if (this.user_info.type < 0) {
            this.commProvider.showToast('请先登录');
        } else {
            this.commProvider.showToast('您还不是VIP用户');
        }
    }

    async getQuotation(type: string) {
        let result = await this.httpService.instance()
            .setUrl('/gold/getQuotation/v2')
            .setQuery({
                type: type
            })
            .getRequest();
        if (result.status == 0) {
            return result.data.result;
        } else {
            return console.log(result.msg);
        }
    }

    async getNewsByChannel(index: number, loader: boolean = true) {
        return await this.httpService.instance()
            .setUrl('/gold/getNewsByChannel')
            .setQuery({
                channelId: this.tab_list[index].key
            })
            .showLoader(loader)
            .getRequest();
    }

    onSegmentChanged(event) {
        console.log('onSegmentChanged:', event._value);
        if (event._value == 'comm_news') {
            this.tab_position = 0;
        } else if (event._value == 'gold_news') {
            this.tab_position = 1;
        }

        this.getNewsByChannel(this.tab_position).then(res => {
            if (res.status == 0) {
                this.news_list[this.tab_position] = res.data.pager.result;
            }
        });
    }

    onItemSelected(quotation: any) {
        if (quotation) {
            this.navCtrl.push('QuotationDetailPage', {data: quotation});
        } else {
            this.navCtrl.push('QuotationPage');
        }
    }

    onInfoDetailSelected(data: any) {
        this.navCtrl.push('InfoDetailPage', {news: data});
    }

    onRefresh(refresher) {
        this.getNewsByChannel(this.tab_position, false).then(res => {
            if (res.status == 0) {
                this.news_list[this.tab_position] = res.data.pager.result;
            }
            refresher.complete();
        });
    }
}
